package com.yxuan.springboot.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yxuan.springboot.WxPayUtil.HttpUtils;
import com.yxuan.springboot.model.Agents;
import com.yxuan.springboot.model.ThirdToken;
import com.yxuan.springboot.service.AgentsService;
import com.yxuan.springboot.service.ThirdTokenService;
import com.yxuan.springboot.util.HttpUtil;
import com.yxuan.springboot.util.IdUtil;
import com.yxuan.springboot.util.Result;
import com.yxuan.springboot.util.WxQRcodeUtil.WeChatQueryObject;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.net.www.content.image.png;

import java.io.*;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
@Api(tags = "微信带参二维码生成接口")
@RequestMapping("/WxQRCode")
public class WxQRCodeController {

    @Autowired
    private ThirdTokenService thirdTokenService;

    @Autowired
    private AgentsService agentsService;

    @ResponseBody
    @RequestMapping("/QRcode")
    public Result getQRcode(String agentId) throws Exception {

        ThirdToken firm = new ThirdToken();
        firm.setTokenType("小程序token");
        ThirdToken tt = thirdTokenService.findObjectByPramas(firm);
        WeChatQueryObject weChatQueryObject = new WeChatQueryObject();
        //设置参数
        //生成代理id
        String scene = "agentId="+agentId;
        Map<String, Object> map = new HashMap<>();
        map.put("scene",scene);
        map.put("env_version","release");//正式版，默认为正式版
        String  url ="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+tt.getAccessToken();
        byte[] wechatQrcodeByHttpClient = getWechatQrcodeByHttpClient(url, map);
        InputStream inputStream = new ByteArrayInputStream(wechatQrcodeByHttpClient);
//        String filePath ="C:\\智创云链\\业务线\\星辰智考\\代理二维码\\"+agentId+".jpg" ;
        String filePath ="/root/upload/images/"+agentId+".jpg" ;
        FileOutputStream out = new FileOutputStream(filePath);
        byte[] buffer = new byte[8192];
        int bytesRead = 0;
        while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
            out.write(buffer, 0, bytesRead);
        }
        out.flush();
        inputStream.close();
        out.close();

        Agents agents = new Agents();
        agents.setAgentid(agentId);
        String fileurl = "https://xc1.haoxnet.com:8098/images/" + agentId + ".jpg";
        agents.setWxQR(fileurl);
        agentsService.upd(agents);

        return new Result(fileurl,200);
    }

    /**
     * @param weChatQueryObject 查询参数
     * @return
     * @throws IOException
     * BufferedInputStream
     */
    public String getWxCode(WeChatQueryObject weChatQueryObject,String access_token) throws IOException {
        if ( weChatQueryObject !=null){
            String  queryURL ="https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+access_token;
            String wxParams = JSON.toJSONString(weChatQueryObject);
            String s = HttpUtil.doPost(queryURL, wxParams);
            return s;
        }
        return null;
    }


    public static void convertBase64ToImage(String base64String, String filePath) throws IOException {
        // 去除Base64字符串前面的data URL部分（如果有）
        if (base64String.startsWith("data:image")) {
            int base64Index = base64String.indexOf("base64,") + "base64,".length();
            base64String = base64String.substring(base64Index);
        }

        // 解码Base64字符串
        byte[] decodedBytes = Base64.getDecoder().decode(base64String);

        // 创建图片文件的完整路径
        File imageFile = new File(filePath);

        // 确保目录存在
        log.info("确保目录存在");
        File directory = imageFile.getParentFile();
        if (!directory.exists()) {
            directory.mkdirs();
        }
        log.info("将解码后的字节写入文件");
        // 将解码后的字节写入文件
        try (FileOutputStream fos = new FileOutputStream(imageFile)) {
            fos.write(decodedBytes);
            fos.flush();
        }
    }

    public byte[] getWechatQrcodeByHttpClient(String url, Map<String, Object> body) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        try {
            StringEntity entity = new StringEntity(JSONObject.toJSONString(body));
            entity.setContentType("image/png");
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);
            try (InputStream inputStream = response.getEntity().getContent();
                 ByteArrayOutputStream out = new ByteArrayOutputStream()) {
                byte[] buffer = new byte[1024];
                int len = -1;
                while ((len = inputStream.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                return out.toByteArray();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }




}
